package gocache

import (
	"gitee.com/yelhjt/gocache/config"
	"gitee.com/yelhjt/gocache/core"
	"gitee.com/yelhjt/gocache/drivers"
)

// unit 类型
type Config interface {
	config.LocalConfig | config.RedisConfig
}

/**
 * 实例化
 * 根据配置选择驱动
 */
func NewCache[conf Config](c conf) (cache core.CacheInterface) {
	var local_config *config.LocalConfig
	// 泛型必须先赋值 interface 才能用switch
	var ti interface{} = &c
	switch v := ti.(type) {
	case *config.LocalConfig:
		//local
		local_config = v
	case *config.RedisConfig:
		// redis
		cache = drivers.NewRedis(redisCacheConfig(v))
	default:
		// 报错，没有该驱动
		panic(core.NoCacheDriver)
	}
	if cache == nil {
		cache = drivers.NewLocal(localCacheConfig(local_config))
	}
	return
}

/**
 * 获取本地配置
 */
func localCacheConfig(conf *config.LocalConfig) *config.LocalConfig {
	if conf.BogRegister == nil {
		// gob 需要注册的类型
		conf.BogRegister = []interface{}{
			map[string]int{},
			map[int]int{},
			map[string]string{},
			map[int]string{},
			map[string]interface{}{},
		}
	}
	if conf.Path == "" {
		conf.Path = "./runtime/cache" // 文件存储路径
	}
	if conf.Config == nil {
		conf.Config = &config.Config{
			Prefix: "",
		}
	}
	return conf
}

/**
 * 获取redis 默认配置
 */
func redisCacheConfig(conf *config.RedisConfig) *config.RedisConfig {
	if conf.Addr == "" {
		conf.Addr = "127.0.0.1" // 主机地址
	}
	if conf.Port == "" {
		conf.Port = "6380" // 端口
	}
	if conf.DBnum == 0 {
		conf.DBnum = 0 // 数据库位置
	}
	if conf.Config == nil {
		conf.Config = &config.Config{
			Prefix: "",
		}
	}
	return conf
}
